import axios from 'axios';

// 创建axios实例
const api = axios.create({
  baseURL: process.env.REACT_APP_API_BASE_URL || '',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    console.log('API Request:', config.method?.toUpperCase(), config.url, config.data);
    return config;
  },
  (error) => {
    console.error('API Request Error:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    console.log('API Response:', response.status, response.data);
    return response;
  },
  (error) => {
    console.error('API Response Error:', error.response?.data || error.message);
    return Promise.reject(error);
  }
);

// 聊天API
export const chatAPI = {
  // 发送消息
  sendMessage: async (message, sessionId = null, systemContext = null) => {
    const response = await api.post('/api/chat/send', {
      message,
      session_id: sessionId,
      system_context: systemContext,
    });
    return response.data;
  },

  // 获取会话消息历史
  getSessionMessages: async (sessionId, limit = 50) => {
    const response = await api.get(`/api/chat/session/${sessionId}/messages`, {
      params: { limit },
    });
    return response.data;
  },

  // 获取会话摘要
  getSessionSummary: async (sessionId) => {
    const response = await api.get(`/api/chat/session/${sessionId}/summary`);
    return response.data;
  },

  // 创建新会话
  createNewSession: async (systemContext = null) => {
    const response = await api.post('/api/chat/session/new', {
      system_context: systemContext,
    });
    return response.data;
  },

  // 删除会话
  deleteSession: async (sessionId) => {
    const response = await api.delete(`/api/chat/session/${sessionId}`);
    return response.data;
  },

  // 获取会话列表
  getSessions: async (limit = 20, keyword = null) => {
    const params = { limit };
    if (keyword) {
      params.keyword = keyword;
    }
    const response = await api.get('/api/chat/sessions', { params });
    return response.data;
  },
};



// 系统API
export const systemAPI = {
  // 获取系统信息
  getSystemInfo: async () => {
    const response = await api.get('/api/info');
    return response.data;
  },

  // 健康检查
  healthCheck: async () => {
    const response = await api.get('/health');
    return response.data;
  },
};

export default api;
